package com.chaos.auth.api.dto.userdetails;

import cn.hutool.core.collection.CollectionUtil;
import com.chaos.auth.api.data.RbacUserData;
import com.chaos.auth.api.enums.UserStatusEnums;
import com.chaos.framework.model.constant.Constants;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;


@Data
public class AdminUserDetails implements UserDetails {
    //使用 RbacUserID
    private Long adminId;

    private String username;
    private String password;

    private Boolean enabled;

    private String authenticationIdentity;

    @ApiModelProperty(value = "phone")
    private String phone;

    @ApiModelProperty(value = "租户id")
    private Long tenantId;

    private Collection<SimpleGrantedAuthority> authorities;

    private Integer status;


    /**
     * 用户信息构建
     *
     * @param userData 用户参数信息
     */
    public AdminUserDetails(RbacUserData userData, Set<Long> roles) {
        this.setAdminId(userData.getId());
        this.setUsername(userData.getUsername());
        this.setPassword(userData.getPassword());
        this.setEnabled(userData.getStatus().equals(UserStatusEnums.IN_SERVICE.getCode()));
        this.setPhone(userData.getMobile());
        this.setStatus(userData.getStatus());
        this.setTenantId(userData.getTenantId());
        if (CollectionUtil.isNotEmpty(roles)) {
            authorities = new ArrayList<>();
            roles.forEach(role -> authorities.add(new SimpleGrantedAuthority(role.toString())));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.getStatus().equals(UserStatusEnums.IN_SERVICE.getCode());
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return false;
    }

    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
